﻿namespace Whut.ObjectSharePointMapper.Internals
{
    using System;
    using System.Globalization;
    using Microsoft.SharePoint;

    public class FindByIdAction : SharePointAction
    {
        public SPWeb Web { get; set; }

        public FindByIdAction(SPWeb web, MetaDataStore metaDataStore, SessionLevelCache sessionLevelCache, EntityHydrater entityHydrater)
            : base(metaDataStore, sessionLevelCache, entityHydrater)
        {
            this.Web = web;
        }

        public TEntity Find<TEntity>(int id)
        {
            if (id < 1)
            {
                return default(TEntity);
            }

            TEntity entity = this.SessionLevelCache.TryFindEntity<TEntity>(id);
            if (entity != null)
            {
                return entity;
            }

            ListInfo listInfo = this.MetaDataStore.GetListInfoFor<TEntity>();
            SPList list = this.Web.GetListByRelativeUrl(listInfo.ListRelativeUrl);
            SPQuery query = new SPQuery()
            {
                Query = "<Where><Eq><FieldRef ID='" + listInfo.Id.FieldId + "' /><Value Type='Counter'>" + id.ToString(CultureInfo.InvariantCulture) + "</Value></Eq></Where>",
                // ViewFields = CamlGenerator.GetCamlQueryViewFields(listInfo),
                RowLimit = 1,
                ItemIdQuery = true,
                //IncludeMandatoryColumns = false
            };
            SPListItemCollection items = list.GetItems(query);
            if (items.Count == 0)
            {
                return default(TEntity);
            }

            return this.EntityHydrater.Hydrate<TEntity>(items[0]);
        }
    }
}
